package org.colafries.common.utils.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Map;

/**
 * @author Ann
 * @version v1.0
 * @ClassName DropDownHandler
 * @Description
 * @date Created in 2025/3/27
 **/
public class DropDownHandler implements SheetWriteHandler {
    private final Map<Integer, String[]> dropDownOptions;

    public DropDownHandler(Map<Integer, String[]> dropDownOptions){
        this.dropDownOptions = dropDownOptions;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 给每一列设置下拉框选项
        for (Map.Entry<Integer, String[]> entry : dropDownOptions.entrySet()){
            Integer columnIndex = entry.getKey();
            String[] options = entry.getValue();

            Sheet sheet = writeSheetHolder.getSheet();
            DataValidationHelper helper = sheet.getDataValidationHelper();

            // 1. 定义下拉选项
            DataValidationConstraint constraint = helper.createExplicitListConstraint(options);

            // 2. 设置下拉范围（从第2行开始，避免表头）
            CellRangeAddressList addressList = new CellRangeAddressList(
                    1,  // 起始行（第2行）
                    65535,  // 结束行（最大行数）
                    columnIndex,  // 列索引
                    columnIndex   // 列索引
            );

            // 3. 应用数据验证
            DataValidation validation = helper.createValidation(constraint, addressList);
            sheet.addValidationData(validation);
        }
    }
}
